package com.bookrecommendation.client.database;

import com.bookrecommendation.client.GWTEntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class RequestListUserBook {

	// http://jsonpfy.dinnerwithf.appspot.com/ListDataService?
	// kind=UserBook;

	private static String url = "http://jsonpfy.dinnerwithf.appspot.com/ListDataService";

	public static void get() {

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		String urlGet = url + "?kind=UserBook";

		jsonp.requestObject(urlGet, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject entries = new JSONObject(feed);

				for (int i = 0; i < entries.size(); i++) {

					JSONObject entry = (JSONObject) entries.get(i + "");

					String[] booksIDs = ConvertJsonp.convertToString(
							entry.get("bookIDs")).split(",");

					boolean recommendedUser = false;

					for (String bookID : booksIDs) {

						GWTEntryPoint.facebookTopBooks.put(bookID,
								GWTEntryPoint.addValue(
										GWTEntryPoint.facebookTopBooks, bookID));

						if (GWTEntryPoint.facebookUserBooks.get(bookID) != null) {

							recommendedUser = true;
						}
					}

					if (recommendedUser) {

						for (String bookID : booksIDs) {

							if (GWTEntryPoint.facebookUserBooks.get(bookID) == null) {

								GWTEntryPoint.facebookTopBooksRecommended.put(
										bookID,
										GWTEntryPoint
												.addValue(
														GWTEntryPoint.facebookTopBooksRecommended,
														bookID));
							}
						}
					}
				}
			}
		});
	}
}
